using System;
using System.Diagnostics;
using System.Threading;

namespace WIT.DAQ.Assistant;

internal static class Program
{
	[STAThread]
	private static void Main(string[] args)
	{
		if (args.Length != 0)
		{
			string text = args[0];
			if (text == "RestartProcess")
			{
				RestartProcess(args);
			}
		}
	}

	private static void RestartProcess(string[] args)
	{
		if (args.Length != 4)
		{
			return;
		}
		string processName = args[2];
		string fileName = args[3];
		if (!int.TryParse(args[1], out var delay) || delay <= 0)
		{
			try
			{
				KillProcess(processName);
			}
			catch
			{
			}
		}
		new Thread((ThreadStart)delegate
		{
			Thread.Sleep(1000 * delay);
			if (Process.GetProcessesByName(processName).Length != 0)
			{
				try
				{
					KillProcess(processName);
				}
				catch
				{
					return;
				}
				do
				{
					Thread.Sleep(100);
				}
				while (Process.GetProcessesByName(processName).Length != 0);
				Process.Start(fileName);
				int num = 10;
				while (num-- >= 0)
				{
					if (Process.GetProcessesByName(processName).Length != 0)
					{
						LocalLog.Log("重启了程序：" + fileName, "event");
						break;
					}
					Thread.Sleep(1000);
				}
			}
		}).Start();
	}

	private static void KillProcess(string processName)
	{
		Process[] processesByName = Process.GetProcessesByName(processName);
		for (int i = 0; i < processesByName.Length; i++)
		{
			processesByName[i].Kill();
		}
	}
}
